package com.ksyun.cloudhostalarmprocessing.service.Impl;

import com.ksyun.cloudhostalarmprocessing.common.QueryRequest;
import com.ksyun.cloudhostalarmprocessing.common.QueryResponse;
import com.ksyun.cloudhostalarmprocessing.common.Request;
import com.ksyun.cloudhostalarmprocessing.entity.Alerts;
import com.ksyun.cloudhostalarmprocessing.entity.vo.AlertDataVO;
import com.ksyun.cloudhostalarmprocessing.entity.vo.AlertVo;
import com.ksyun.cloudhostalarmprocessing.mapper.AlertsMapper;
import com.ksyun.cloudhostalarmprocessing.service.IAlertsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 李厚航
 * @since 2024-05-07
 */
@Service
public class AlertsServiceImpl implements IAlertsService {

    @Resource
    private AlertsMapper alertsMapper;

    @Override
    @Transactional
    public Integer add(Alerts alerts) {
        return alertsMapper.create(alerts);
    }

    @Override
    public List<AlertVo> findAlert(Integer page,Integer size) {
        return alertsMapper.findAlert(page,size);
    }

    @Override
    @Transactional
    public QueryResponse<AlertDataVO> getByTimeStamp(QueryRequest queryRequest) {
        List<AlertDataVO> alertDataVOS = alertsMapper.selectByTimeStamp(queryRequest.getStart(), queryRequest.getEnd());
        HashMap<String, String> map = new HashMap<>();
        map.put("宕机","up==0");
        map.put("主机连接数过高","node_netstat_Tcp_CurrEstab>1000");
        map.put("磁盘空间剩余不足","node_filesystem_free_bytes<1*1024*1024");
        map.put("5分钟内cpu负载过高","node_load5 >= 10");
        map.put("空间内存过低","node_memory_MemFree_bytes<=100*1024");
        map.put("主机内存使用率超过80","(1-((node_memory_Buffers_bytes + node_memory_Cached_bytes + node_memory_MemFree_bytes)/node_memory_MemTotal_bytes))*100 > 80");
        map.put("主机网卡入口流量过高","rate(node_network_receive_bytes_total[1m])/1024/1024>100");
        return new QueryResponse<>(queryRequest.getRequestId(), alertDataVOS.size(),alertDataVOS.stream().map(data -> new AlertDataVO(map.get(data.getCondition()),data.getTimestamp(),data.getValue())).collect(Collectors.toList()));
    }

    @Override
    public Integer selectCount() {
        return alertsMapper.selectCount();
    }
}
